<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请输入SPU名称"
          v-model="SpuParams.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择SPU品牌" v-model="SpuParams.tmId">
          <el-option
            v-for="(item, index) in AllTradeMark"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入相关描述"
          v-model="SpuParams.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="ImageList"
          action="//admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handlerUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            alt="Preview Image"
            style="width: 100%; height: 100%"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select
          v-model="saleAttrIdAndValueName"
          :placeholder="
            unSelectSaleAttr.length ? '请选择SPU销售属性' : '暂无数据可选择'
          "
          style="width: 240px"
        >
          <el-option
            v-for="(item, index) in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="plus"
          style="margin: 10px 5px"
          size="small"
          :disabled="!saleAttrIdAndValueName"
          @click="addSaleAttr"
        >
          添加属性
        </el-button>
        <!-- 展示销售属性与属性值 -->
        <el-table border :data="SaleAttrValue">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="销售属性名"
            align="center"
            width="120"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="销售属性值">
            <template #="{ row, $index }">
              <el-tag
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="item.id"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                class="mx-1"
                closable
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.flag"
                v-model="row.saleAttrValue"
                placeholder="请输入属性值"
                size="small"
                style="width: 100px"
                @blur="toLook(row)"
              ></el-input>
              <el-button
                v-else
                type="primary"
                size="small"
                icon="plus"
                @click="toEdit(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                icon="delete"
                @click="SaleAttrValue.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="save"
          :disabled="!SaleAttrValue.length"
        >
          保存
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
let $emit = defineEmits(['changeScene'])
import { computed, ref } from 'vue'
import {
  reqAllTrademark,
  reqSpuImageList,
  reqSpuSaleAttrList,
  reqAllSaleAttr,
  reqAddOrUpdateSPU,
} from '@/api/product/spu'
import {
  SpuData,
  Trademark,
  AllTrademark,
  SpuImg,
  SaleAttr,
  SpuImgResponseData,
  SaleAttrReponseData,
  SaleAttrList,
  SaleAttrListResponseData,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'
// 取消按钮的回调
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}
// 存储SPU数据
let AllTradeMark = ref<Trademark[]>([])
// 商品图片
let ImageList = ref<SpuImg[]>([])
// SPU销售属性
let SaleAttrValue = ref<SaleAttr[]>([])
// 全部销售属性
let AllSaleAttr = ref<SaleAttrList[]>([])
// 控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
// 存储预览图片地址
let dialogImageUrl = ref<string>('')
// 存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
// 收集还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')
// 子组件中的请求数据的方法
const initSpuData = async (spu: SpuData) => {
  // 存储已有的SPU对象
  SpuParams.value = spu
  // spu：即为父组件出传递的SPU对象
  // 获取全部品牌数据
  let allTrademark: AllTrademark = await reqAllTrademark()
  // 获取某个品牌全部售卖商品的图片
  let imageList: SpuImgResponseData = await reqSpuImageList(spu.id as number)
  // 获取SPU的销售属性
  let saleAttrList: SaleAttrReponseData = await reqSpuSaleAttrList(
    spu.id as number,
  )
  // 获取全部SPU销售属性
  let allSaleAttr: SaleAttrListResponseData = await reqAllSaleAttr()
  AllTradeMark.value = allTrademark.data
  //SPU对应商品图片
  ImageList.value = imageList.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  SaleAttrValue.value = saleAttrList.data
  AllSaleAttr.value = allSaleAttr.data
}

// 照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
// 照片墙删除文件钩子
const handleRemove = () => {}
// 照片墙上传之前的钩子
const handlerUpload = (file: any) => {
  if (
    file.type == 'image/png' ||
    file.type == 'image/jpeg' ||
    file.type == 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必PNG|JPG|GIF',
    })
    return false
  }
}
// 计算当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  //  全部销售属性：颜色、版本、尺码

  let unSelectAttr = AllSaleAttr.value.filter((item) => {
    return SaleAttrValue.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectAttr
})
// 添加销售属性的方法
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  // 准备一个新的销售属性对象：将来带给服务器即可
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  // 追加到数组当中
  SaleAttrValue.value.push(newSaleAttr)
  // 清空收集的数据
  saleAttrIdAndValueName.value = ''
}
// 销售属性值按钮的点击事件
const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
// 表单元素失去焦点
const toLook = (row: SaleAttr) => {
  // 整理收集的属性的ID与属性值
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrValue: any = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  // 非法情况判断
  if (saleAttrValue?.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 判断属性值是否在数组当中存在
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }
  // 追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}
// 保存按钮的回调
const save = async () => {
  // 整理参数
  // 照片墙的数据
  SpuParams.value.spuImageList = ImageList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  // 销售属性的数据
  SpuParams.value.spuSaleAttrList = SaleAttrValue.value

  // 发请求：添加SPU|更新已有的SPU
  let result = await reqAddOrUpdateSPU(SpuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    // 切换页面组件
    $emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
// 添加新的SPU初始化请求方法
const initAddSpu = async (id: number) => {
  // 清空数据
  Object.assign(SpuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  ImageList.value = []
  SaleAttrValue.value = []
  saleAttrIdAndValueName.value = ''
  // 存储三级分类的ID
  SpuParams.value.category3Id = id
  // 获取全部品牌数据
  let allTrademark: AllTrademark = await reqAllTrademark()
  // 获取全部SPU销售属性
  let allSaleAttr: SaleAttrListResponseData = await reqAllSaleAttr()
  // 存储数据
  AllTradeMark.value = allTrademark.data
  AllSaleAttr.value = allSaleAttr.data
}
// 对外暴露
defineExpose({ initSpuData, initAddSpu })
</script>

<style lang="scss" scoped></style>
